package com.wenlin.myproduction.util;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import com.wenlin.myproduction.bean.InOutRecordBean;

import java.util.ArrayList;
import java.util.List;

/**
 * @desc: 数据管理
 * @author: 文琳
 * @time: 2025/11/12 周三 15:23
 */
public class InOutDataManager {
    private static final String KEY = "InOutData";

    public static List<InOutRecordBean> getList() {
        String json = SPUtils.getInstance().getString(KEY);
        List<InOutRecordBean> list = null;
        if (Checker.hasWord(json)) {
            try {
                list = new Gson().fromJson(json, new TypeToken<List<InOutRecordBean>>() {
                }.getType());
            } catch (JsonParseException e) {
                e.printStackTrace();
            }
        }
        if (list == null) list = new ArrayList<>();
        return list;
    }

    public static void save(List<InOutRecordBean> list) {
        try {
            String json = new Gson().toJson(list);
            SPUtils.getInstance().put(KEY, json);
        } catch (JsonParseException e) {
            e.printStackTrace();
        }
    }

    public static void add(InOutRecordBean bean) {
        List<InOutRecordBean> list = getList();
        list.add(0, bean);
        save(list);
    }

    public static void remove(String createTime) {
        List<InOutRecordBean> list = getList();
        if (!list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getCreateTime().equals(createTime)) {
                    list.remove(i);
                    break;
                }
            }
        }
        save(list);
    }

    public static void update(int updatePosition, String str){
        String [] arr = InOutUtil.getDateDescAndMoneyArrayByRegex(str);
        List<InOutRecordBean> list = getList();
        InOutRecordBean iorb = list.get(updatePosition);
        iorb.setDate(arr[0]);
        iorb.setDesc(arr[1]);
        iorb.setMoney(arr[2]);
        save(list);
    }
}
